/**
 * Project: ServletDemo
 * File Created at 2012-8-26下午11:19:48
 */
package demo.other.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 
 * @author Administrator
 * 2012-8-26下午11:19:48
 */
public class SocketWebPageTest {

    String host="www.baidu.com";
    int port=80;
    Socket socket=null;
    
    public void createSocket()throws Exception{
     socket=new Socket(host,80);
    }
    
    public void communicate()throws Exception{
     StringBuffer sb=new StringBuffer("GET "+"/"+" HTTP/1.1\r\n");
     sb.append("Host:www.baidu.com\r\n");
     sb.append("Accept: */*\r\n");
     sb.append("Accept-Language: zh-cn\r\n");
     sb.append("Accept-Encoding: gb2312\r\n");
     sb.append("User-Agent: Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.0)\r\n");
     sb.append("Connection: Keep-Alive\r\n\r\n");
     
     //send http request
     OutputStream socketout=socket.getOutputStream();
     socketout.write(sb.toString().getBytes());
     socket.shutdownOutput();
     
     //receive result
     InputStream socketIn=socket.getInputStream();
     BufferedReader br=new BufferedReader(new InputStreamReader(socketIn));
     String data=null;
     while((data=br.readLine())!=null){
      System.out.println(data);
     }

        socket.close();
    }
    
    public static void main(String args[]){
        SocketWebPageTest client=new SocketWebPageTest();
    try {
    client.createSocket();
 } catch (Exception e) {
   
    e.printStackTrace();
 }
    try {
    client.communicate();
 } catch (Exception e) {
   
    e.printStackTrace();
 }
    }
}
